<template>
  <div class="app-container">
    <el-page-header @back="$router.push({ path: 'index' })" content="组件编辑">
    </el-page-header>
    <br />
    <el-row>
      <el-button type="primary" @click="commit">保存</el-button>
      <el-button @click="$refs.previewForm.show({ id: form.id })"
        >预览</el-button
      >
    </el-row>
    <br />
    <el-card class="box-card">
      <el-form ref="form" :model="form" label-width="80px" label-position="top">
        <el-form-item label="封面">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :action="$store.getters['app/resourceUploadUrl']"
            :on-success="onCoverUploadSuccessHandler"
          >
            <img
              v-if="form.cover.fileId"
              :src="form.cover.fileId|getResourceUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="名称">
          <el-input type="text" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="中间件">
          <el-upload
            class="upload-demo"
            :action="$store.getters['app/resourceUploadUrl']"
            :show-file-list="false"
            :on-success="onResourceUploadSuccessHandler"
          >
            <el-button size="small" type="primary" plain>上传中间件 </el-button>
          </el-upload>
          <span>
            <el-button
              v-if="
                form.middleware.fileName && form.middleware.fileName.length > 0
              "
              type="text"
              @click="handleMiddlewareResourceRemove()"
              >删除</el-button
            >
            <span>&nbsp;&nbsp;{{ form.middleware.fileName }}</span>
          </span>
        </el-form-item>
        <el-form-item label="中间件入口（全类名）">
          <el-input type="text" v-model="form.middlewareEntry"></el-input>
        </el-form-item>
        <el-form-item label="是否主动推送">
          <el-checkbox label="主动推送" v-model="form.isPush"></el-checkbox>
        </el-form-item>

        <el-form-item label="刷新频率(ms)" v-if="form.isPush">
          <el-input
            type="number"
            size="mini"
            v-model="form.updateFrequency"
          ></el-input>
        </el-form-item>
        <el-form-item label="参数">
          <el-row>
            <el-button size="small" type="primary" plain @click="addParameter"
              >新增参数</el-button
            >
          </el-row>
          <br />
          <el-table
            v-loading="listLoading"
            :data="form.parameters"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            size="mini"
          >
            <el-table-column
              align="center"
              label="操作"
              prop="order"
              width="95"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="deleteParameter(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="Permission" width="150" align="center">
              <template slot-scope="scope">
                <el-checkbox
                  label="公开"
                  v-model="scope.row.isPublic"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="IsRequired"
              prop="order"
              width="95"
            >
              <template slot-scope="scope">
                <el-checkbox
                  label="必填"
                  v-model="scope.row.required"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="Name" width="150" align="center">
              <template slot-scope="scope">
                <el-input
                  type="text"
                  size="mini"
                  v-model="scope.row.name"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="Value">
              <template slot-scope="scope">
                <el-input
                  type="textarea"
                  size="mini"
                  v-model="scope.row.value"
                  :autosize="{ minRows: 1, maxRows: 4 }"
                ></el-input>
                 <el-input
                  type="textarea"
                  size="mini"
                  v-model="scope.row.description"
                  placeholder="参数描述"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
          <br />
        </el-form-item>
      </el-form>
    </el-card>
    <previewForm ref="previewForm"></previewForm>
  </div>
</template>

<script>
import { getList } from "@/api/table";

import resourceApi from "@/api/resource";
import previewForm from "./previewForm";

export default {
  components: { previewForm },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    },
    getResourceUrl(fileId) {
      debugger;
      return resourceApi.getResourceUrl(fileId);
    },
  },
  data() {
    return {
      form: {
        id: null,
        cover: {
          fileId: "",
          fileName: ""
        },
        description: "",
        middleware: {
          fileId: "",
          fileName: ""
        },
        middlewareEntry: "",
        name: "",
        parameters: [
          {
            name: "",
            description: "",
            isPublic: true,
            required: true,
            value: ""
          }
        ],
        isPush: true,
        updateFrequency: 0
      }
    };
  },
  computed: {},
  created() {
    this.listLoading = false;
  },
  mounted() {
    this.loadData();
  },
  methods: {
    loadData() {
      debugger;
      this.loading = true;
      if (!this.$route.query.id) return;
      this.$store
        .dispatch("middleware/get", this.$route.query.id)
        .then(res => {
          res.cover = res.cover || {};
          res.middleware = res.middleware || {};
          res.parameters = res.parameters || [];
          debugger;
          this.form = res;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    commit(callback) {
      debugger;
      const _this = this;

      var action = this.$route.query.id ? "update" : "create";
      return this.$refs["form"]
        .validate()
        .then(() => {
          this.loading = true;
          debugger;
          this.$store
            .dispatch("middleware/" + action, _this.form)
            .then(res => {
              this.loading = false;
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              if(action=='create')
                this.$router.go(-1)
            })
            .catch(() => {
              this.loading = false;
            });
        })

        .catch(e => {
          _this.loading = false;
          console.log("error submit!!");
        });
    },
    
    onCoverUploadSuccessHandler(response, file, fileList) {
      debugger;
      let fileItem = response.data[0];

      if (!this.form.cover) this.$set(this.form, "cover", {});

      this.$set(this.form.cover, "fileId", fileItem.id);
      this.$set(this.form.cover, "fileName", fileItem.fileName);
    },
    onResourceUploadSuccessHandler(response, file, fileList) {
      debugger;
      let fileItem = response.data[0];

      if (!this.form.middleware) this.$set(this.form, "middleware", {});

      this.$set(this.form.middleware, "fileId", fileItem.id);
      this.$set(this.form.middleware, "fileName", fileItem.fileName);
    },
    deleteResource(index) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (!this.form.middleware) this.$set(this.form, "middleware", {});

        this.$set(this.form.middleware, "fileId", null);
        this.$set(this.form.middleware, "fileName", null);
      });
    },
    addParameter() {
      this.form.parameters.push({
        name: "",
        isPublic: true,
        required: false,
        value: ""
      });
    },
    deleteParameter(index) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.form.parameters.splice(index, 1);
      });
    },
    handleMiddlewareResourceRemove() {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$set(this.form.middleware, "fileId", "");
        this.$set(this.form.middleware, "fileName", "");
      });
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
